using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;

namespace jSLCore.Client.Presentation.Controls
{
    [ContentProperty("Content")]
    public partial class jNullableBox : ContentControl
    {
        public jNullableBox()
        {
            DefaultStyleKey = typeof (jNullableBox);

            IsTabStop = false;

            Loaded += (sender, args) =>
                          {
                              var deleteButton = GetTemplateChild("PART_deleteButton") as DeleteButton;
                              if (deleteButton != null) deleteButton.Click += (o, eventArgs) => NullaleIt();

                              if (Content != null)
                              {
                                  Margin = ((FrameworkElement) Content).Margin;
                                  ((FrameworkElement) Content).Margin = new Thickness(0);
                              }
                          };
        }

        internal void NullaleIt()
        {

            if (Nullale != null)
            {
                InvokeNullale();
            }
            else
            {
                SLWPFSelectorNullale();
                
                if (Combo != null)
                {
                    Combo.SelectedIndex = -1;
                }
                
                if (TextBox != null)
                {
                    TextBox.Text = string.Empty;
                }
                if (TextBlock != null)
                {
                    TextBlock.Text = null;
                }
            }
        }

        partial void SLWPFSelectorNullale();

        public event EventHandler Nullale;

        public void InvokeNullale()
        {
            EventHandler handler = Nullale;
            if (handler != null) handler(this, EventArgs.Empty);
        }
        

        public Selector Combo { get
        {
            if (Content is ErrorBorder) return ((ErrorBorder)Content).Content as Selector;
            return Content as ComboBox;
        } }

      

        public TextBox TextBox { get
        {
            if (Content is ErrorBorder) return ((ErrorBorder)Content).Content as TextBox;
            return Content as TextBox;
        } }

        public TextBlock TextBlock { get
        {
            if (Content is ErrorBorder) return ((ErrorBorder)Content).Content as TextBlock;
            return Content as TextBlock;
        } }
    }
}